<?php
declare(strict_types=1);

namespace app\appointment\controller;

use app\appointment\service\passport\Login as LoginService;
use app\appointment\model\Employee as EmployeeModel;

class Employee extends Controller
{
    public function bind($employeeId)
    {
        // 查看该员工是否已绑定
        $model = EmployeeModel::get($employeeId);
        if($model->user_id > 0) {
          // 已绑定
          return $this->renderError('该员工已被绑定！');
        }

        $user = $this->getLoginUser(false);
        $LoginService = new LoginService();
        if (!$user) {
            // 若用户不存在，则创建用户
            
            $userId = $LoginService->bindMpUser($this->postForm());
            if (empty($userId)) {
                return $this->renderError($LoginService->getError());
            }

            // 获取登录成功后的用户信息
            $user = $LoginService->getUserInfo();
        }else {
          // 用户已存在，更新一下用户信息
          $LoginService->updateUser($user, true, $this->postForm()['partyData']);
        }
        $userId = $user->user_id;
        // 若该员工已绑定，则不能再次绑定
        if(EmployeeModel::get(['user_id' => $userId])) {
          return $this->renderError('绑定失败，您已经绑定过其他员工');
        }

        if(!$model->bind($userId)) {
          return $this->renderError($model->getError() ?: '绑定失败，请重试');
        }

        return $this->renderSuccess('绑定成功');
    }

    public function detail($employeeId)
    {
      $employee = EmployeeModel::get($employeeId);
      return $this->renderSuccess(compact('employee'));
    }
}
